package com.crm.controller;

import com.crm.entity.Department;
import com.crm.entity.Student;
import com.crm.repository.StudentRepositoy;
import com.crm.service.StudentService;
import com.crm.util.EasyPoiUtils;
import com.crm.util.ResultInfoUtil;
import com.crm.websocket.WebSocket;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 
 * @date 2020/5/13 18:21
 */
@RestController
@Slf4j
@RequestMapping("/excel")
public class ExcelController {
    //上传文件的路径
    private String path = null;

    @Autowired
    private StudentService studentService;
    @Autowired
    private StudentRepositoy studentRepositoy;
    private static final Logger log=org.slf4j.LoggerFactory.getLogger(ExcelController.class);

    @PostMapping("/upload")
    public Map<String,Object> studentExcel(@RequestParam MultipartFile file) throws IOException {
        Map<String, Object> map = new HashMap<String, Object>();
        // 判断是否为空文件
        if (file.isEmpty()) {
            map.put("msg", "文件不能为空");
            return map;
        }
        // 文件类型
        String contentType = file.getContentType();
        // springmvc处理后的文件名
        String fileName = file.getName();
        log.info("服务器文件名：" + fileName);
        // 原文件名即上传的文件名
        String origFileName = file.getOriginalFilename();
        // 文件大小
        Long fileSize = file.getSize();
        String paths = "C:/Users/18744/Documents/workspace-spring-tool-suite-4-4.5.1.RELEASE/springboot-resources/src/main/resources/static/excel/";
        String absolutePath = paths + origFileName;
        System.out.println(absolutePath);
        path = absolutePath;// 文件地址存入全局变量，上传成功执行写入回调此路径
        System.out.println(absolutePath);
        System.out.println(path);
        // 保存文件
        // 可以使用二进制流直接保存
        // 这里直接使用transferTo
        file.transferTo(new File(absolutePath));

        map.put("文件名字", origFileName);
        map.put("文件类型", contentType);
        map.put("文件大小", fileSize);
        map.put("code", 0);
        System.out.println(map);
        return map;
        // return String.format(file.getClass().getName() +
        // "方式文件上传成功！\n文件名:%s,文件类型:%s,文件大小:%s", origFileName, contentType,fileSize);
    }

    /**
     * 学生导出
     *
     * @return
     */
    @GetMapping("/stuout11")
    public void StudentExportExcel(HttpServletResponse response, String ids) {
        List<Student> eList = studentRepositoy.findAll();
        String name = Student.class.getSimpleName() + ".xls";// 获取类名

        if (ids != null && ids != "") {
            // 导出选中的
            List<Long> listIds = Arrays.asList(ids.split(",")).stream().map(s -> Long.parseLong(s.trim()))
                    .collect(Collectors.toList());
            List<Student> student = new ArrayList<Student>();
            for (Long i : listIds) {
                Integer id = i.intValue();
                Optional<Student> stu = studentRepositoy.findByExcelId(ids);
                student.add(stu.get());
            }
            //核心操作
            EasyPoiUtils.exportExcel(student, Student.class.getSimpleName()+"数据", Student.class.getSimpleName(), Student.class, name, response);
        } else {
            //核心操作
            EasyPoiUtils.exportExcel(eList, Student.class.getSimpleName()+"数据", Student.class.getSimpleName(), Student.class, name, response);
        }
    }

    @RequestMapping("/stuout")
    @GetMapping
    public void find(HttpServletResponse response,String ids) throws IOException {
        Workbook wb = new XSSFWorkbook();
        String headers[] = {"姓名",  "性别","年龄", "电话", "QQ" };
        int rowIndex = 0;
        Sheet sheet = wb.createSheet();
        Row row = sheet.createRow(rowIndex++);
        for (int i = 0; i < headers.length; i++) { // 先写表头
            row.createCell(i).setCellValue(headers[i]);
        }
        String uid[]=null;
        List<Student> list = new ArrayList<>();

        if(ids!=null&&ids!="") {
            uid = ids.split(",");
        }

        if(uid !=null) {
            for(int i =0;i<uid.length;i++) {
                //同过遍历取出字符串里的每个id
                String id=uid[i];
                //Integer id = Integer.parseInt(uid[i]);
                Optional<Student> stu = studentRepositoy.findByExcelId(id);
                System.out.println(stu.get());
                list.add(stu.get());
            }
        }else {
            list = studentRepositoy.findAll();
        }
        //List<User> list = service.getAll();
        for (int i = 0; i < list.size(); i++) {
            row = sheet.createRow(rowIndex++);
            //row.createCell(0).setCellValue(list.get(i).getUid());
            row.createCell(0).setCellValue(list.get(i).getStuName());

            row.createCell(1).setCellValue(list.get(i).getSex());
            row.createCell(2).setCellValue(list.get(i).getAge());
            //row.createCell(2).setCellValue(list.get(i).getDepartment().getDid()); 咨询师 网络咨询师
          //  row.createCell(3).setCellValue(list.get(i).getDepartment().getDname());
            row.createCell(3).setCellValue(list.get(i).getPhone());
            row.createCell(4).setCellValue(list.get(i).getQQ());
        }
        response.setHeader("Content-Disposition",
                "attachment;filename=" + new String("学生导出excel.xlsx".getBytes("utf-8"), "iso8859-1"));
        response.setContentType("application/ynd.ms-excel;charset=UTF-8");
        OutputStream out = response.getOutputStream();
        wb.write(out);
        out.flush();
        out.close();
    }
     @PostMapping("/stuin")
    public Object addAllSetudent(@RequestParam("fileupload") MultipartFile fileupload, HttpServletRequest request,String userId)
            throws IOException {
    	 userId=request.getParameter("userId");
    	 System.out.println("userId"+userId);
        String originalFilename = fileupload.getOriginalFilename();
        String mypath = "D:\\Downloads" + originalFilename;

        // 上传到本地
        fileupload.transferTo(new File(mypath));
        ResultInfoUtil res= new ResultInfoUtil();
        // Excel读取
        // XSSFWorkbookType fs = WorkbookFactory.create(new FileInputStream(mypath));
        XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(mypath));
        XSSFSheet hssfSheet = wb.getSheetAt(0); // 获取第一个Sheet页

        if (hssfSheet != null) {
            for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
                XSSFRow hssfRow = hssfSheet.getRow(rowNum);
                if (hssfRow != null) {
                    // mysql写入
                    Student student= new Student();

                    ///此处写咨询师和网络咨询师 Department d = new Department();
                    //student.setTid((int) hssfRow.getCell(0).getNumericCellValue());
                    student.setStuName(hssfRow.getCell(0).getStringCellValue());
                    student.setSex(hssfRow.getCell(1).getStringCellValue());
                    student.setAge((int) hssfRow.getCell(2).getNumericCellValue());
                    student.setPhone( hssfRow.getCell(3).getStringCellValue());
                    student.setQQ(hssfRow.getCell(4).getStringCellValue());
                   // d.setDid((int)hssfRow.getCell(2).getNumericCellValue());
                 //   d.setDname(hssfRow.getCell(3).getStringCellValue());
                  //  t.setDepartment(d);
                 //   t.setSex(hssfRow.getCell(4).getStringCellValue());
                  //  t.setAge((int)hssfRow.getCell(5).getNumericCellValue());
                 //   ff.saveAndFlush(t);
                    studentService.addStudent(student,userId);
                    res.setCode(0);
                    res.setMsg("成功");
                }
            }
        }
        return "<script type=\"text/javascript\">\r\n" + "		alert('上传成功');\r\n"
                + "		location.href='http://127.0.0.1:8848/crm管理/student.html';\r\n" + "	</script>";
        //return map;
    }


}
